angular.module('home', ['ui.router', 'toaster'])
    .controller('homeCtrl', function ($scope, $state, $http, $q, toaster) {
        $scope.templateList = [];

        $scope.init = function () {
            $scope.getTemplateList().then(function (data) {
                $scope.templateList = data;
            }, function (obj) {
                toaster.warning(obj.detailMsg);
            });

            $state.go("home.newConfig");
        };

        $scope.tab = function (route) {
            return $state.includes(route);
        };

        $scope.getTemplateList = function(){
            var deferred = $q.defer();
            $http({
                method: 'GET',
                params:{
                    _t:Date.now()
                },
                url: '/tool/calc/template/list'
            }).success(function (retMsg) {
                if (retMsg.success) {
                    deferred.resolve(retMsg.data);
                } else {
                    deferred.reject(retMsg);
                    console.error(retMsg.detailMsg);
                }
            });

            return deferred.promise;
        };
    })
    .controller('templateCtrl', function ($scope, $q, $http, toaster) {
        $scope.init = function () {
            console.info('template...');
        };
    })
    .controller('configCtrl', function ($scope, toaster) {
        $scope.init = function () {
            console.info('config...');
        };
    })
    .controller('newConfigCtrl', function ($scope, $filter, $http, $httpParamSerializer, $q, toaster) {
        $scope.companyList = [];

        $scope.init = function () {
            console.info('new config...');

            $scope.getCompanyList().then(function (data) {
                $scope.baseCompanyList = data;

                //将基础数据拷贝出来
                $scope.companyList = angular.copy($scope.baseCompanyList);
            }, function (obj) {
                toaster.warning(obj.detailMsg);
            });

/*
            //测试用
            $scope.template_rule = "Alarm_XHNY";
            $scope.template_expression = "MHWY#SHAX#MET#ZHYS_X_EM_201#w+MHWY#SHAX#MET#ZHYS_X_EM_202#w[@his]";
            $scope.template_orgId = "e0bc74c4f58611e58c2d507b9d28ddca";
            $scope.template_siteId = "8aaf4fb85474172c01547990053f00be";
*/
        };

        //智能选择组织站点
        $scope.getCompanyList = function (filter) {
            var deferred = $q.defer();
            $http({
                method: 'GET',
                params:{
                    filter: filter,
                    _t:Date.now()
                },
                url: '/tool/common/company/list'
            }).success(function (retMsg) {
                if (retMsg.success) {
                    deferred.resolve(retMsg.data);
                } else {
                    deferred.reject(retMsg);
                    console.error(retMsg.detailMsg);
                }
            });

            return deferred.promise;
        };
        $scope.companyQuery = function () {
            $scope.getCompanyList($scope.template_company_query).then(function (data) {
                $scope.companyList = data;
            });
        };
        $scope.clearCompanyQuery = function () {
            $scope.template_company_query = "";
            $scope.template_orgId = "";
            $scope.template_siteId = "";
            $scope.companyList = angular.copy($scope.baseCompanyList);
        };
        $scope.selectCompany = function (company) {
            $scope.template_company_query = company.siteName;
            $scope.template_orgId = company.orgId;
            $scope.template_siteId = company.siteId;
        };

        //模板选择&预览
        $scope.selectedTemplate = {};
        $scope.paramsArray = [];
        $scope.changeTemplate = function () {
            if ($scope.selectedTemplate != null && $scope.selectedTemplate.params != null) {
                $scope.paramsArray = $scope.$eval($scope.selectedTemplate.params);
                $scope.paramsArray = $filter('orderBy')($scope.paramsArray, "index");
                console.info($scope.paramsArray);
            } else {
                $scope.paramsArray = [];
            }
        };

        $scope.templatePreview = function () {
            var params = [];
            angular.forEach($scope.paramsArray, function (_item) {
                params.push(_item.value);
            });
            var vo = {
                templateId: $scope.selectedTemplate.id,
                name: $scope.template_rule,
                expression: $scope.template_expression,
                orgId: $scope.template_orgId,
                siteId: $scope.template_siteId,
                params: params
            };

            $http({
                method: 'POST',
                url: '/tool/calc/process/buildConfig',
                data: $httpParamSerializer(vo),
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            }).success(function (retMsg) {
                if (retMsg.success) {
                    $scope.preview_html = jsl.format.formatJson(retMsg.data);
                    console.info($scope.preview_html);
                } else {
                    toaster.warning(''+retMsg.detailMsg);
                }
            });
        };
        $scope.sendConfig = function () {
            var params = [];
            angular.forEach($scope.paramsArray, function (_item) {
                params.push(_item.value);
            });
            var vo = {
                templateId: $scope.selectedTemplate.id,
                name: $scope.template_rule,
                expression: $scope.template_expression,
                orgId: $scope.template_orgId,
                siteId: $scope.template_siteId,
                params: params
            };

            $http({
                method: 'POST',
                url: '/tool/calc/publish/sendConfig',
                data: $httpParamSerializer(vo),
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            }).success(function (retMsg) {
                if (retMsg.success) {
                    toaster.success("下发成功。");
                    $scope.preview_html = jsl.format.formatJson(retMsg.data);
                } else {
                    toaster.warning(''+retMsg.detailMsg);
                }
            });
        };
/*
        var par = [
            {
                index: 1,
                name: "规则名称&编号",
                description: "name",
                value: "",
                type: "",
                placeholder: "请填写规则名称，需要保证全局唯一。",
                required: true
            },
            {
                index: 2,
                name: "组织编号",
                description: "orgId",
                value: "_orgId",
                type: "",
                placeholder: "请填写组织编号。",
                required: true
            },
            {
                index: 3,
                name: "站点编号",
                description: "siteId",
                value: "_siteId",
                type: "",
                placeholder: "请填写站点编号。",
                required: true
            }
        ];
*/
    })
;
